<?php
/**
 * Nordic Repository
 * 
 * LICENSE
 * 
 * The new BSD license is applied on this source-file. For further
 * information please visit http://license.nordic-dev.de/newbsd.txt
 * or send an email to andre.moelle@gmail.com.
 */

/**
 * This schema-class is used for encoding and decoding native php
 * data.
 * 
 * @category   Nordic
 * @package    Nordic_Schema
 * @copyright  2007 Nordic Development
 * @license    http://license.nordic-dev.de/newbsd.txt (New-BSD license)
 * @author     Andre Moelle <andre.moelle@gmail.com>
 * @author     Stephan Moelle <s-moelle@gmx.de>
 * @version    $Id: Php.php 3 2007-07-08 09:21:42Z andre.moelle $
 */
class Nordic_Schema_Php implements Nordic_Schema_Interface
{
	/**
	 * This method converts an array to readable text.
	 * 
	 * The format converted can be evaluated easily. You only have
	 * to run eval over the result to get the array as an php-array.
	 * 
	 * @access private
	 * @param Array $array array to convert
	 * @param Integer $dim dimension in which we are
	 * @return String
	 */
	private function _convertArray($array, $dim = 0) 
	{ 
		$result = '';
		
		if(!is_array($array) || count($array) == 0)
			return '';
		
		if($dim == 0)
 			$result = 'return ';
 		
 		$result .= 'array(' . "\n";
		
		foreach($array as $key => $value)
		{
			$result .= str_repeat("\t", $dim + 1) . "'" . $key . "' => ";
			
			if(is_array($value))
			{
				$result .= 
					$this->_convertArray($value, $dim + 1) . ",\n";
			}
			else 
			{
				$result .= "'" . $value . "',\n"; 
			}
		}
		
		return $result;
	}
	
	/**
	 * @see Nordic_Schema_Interface::decode()
	 */
	public function decode ($array)
	{
		return $this->_convertArray($array);
	}
	
	/**
	 * @see Nordic_Schema_Interface::encode()
	 */
	public function encode ($string)
	{
		return eval($string);
	}
}
?>